package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.mapper.ProductMapper;
import cn.tedu.coolshark.pojo.dto.ProductDto;
import cn.tedu.coolshark.pojo.dto.ProductUpdateDto;
import cn.tedu.coolshark.pojo.entity.Product;
import cn.tedu.coolshark.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Value("${imagesPath}")
    public String dirPath;

    @Autowired
    ProductMapper mapper;

    @RequestMapping("/insert")
    public int insert(@RequestBody ProductDto productDto){
        Product product = new Product();
        BeanUtils.copyProperties(productDto,product);
        product.setCreated(new Date());
        product.setViewCount(0);

        return mapper.insert(product);
    }

    @RequestMapping("/select")
    public List<ProductAdminVo> select(){
        return mapper.selectForAdmin();
    }

    @RequestMapping("/delete")
    public int delete(int id){
        String url = mapper.selectUrlById(id);
        new File(dirPath+url).delete();
        return mapper.deleteById(id);
    }

    @RequestMapping("/selectById")
    public ProductUpdateVo selectById(int id){
        return mapper.selectById(id);
    }

    @RequestMapping("/update")
    public int update(@RequestBody ProductUpdateDto productUpdateDto){
        String url = mapper.selectUrlById(productUpdateDto.getId());
        if(!url.equals(productUpdateDto.getUrl())){
            new File(dirPath+url).delete();
        }

        Product product = new Product();
        BeanUtils.copyProperties(productUpdateDto, product);

        return mapper.update(product);
    }

    @RequestMapping("/top")
    public List<ProductTopVo> top(){
        return mapper.selectTop();
    }

    @RequestMapping("/index")
    public List<ProductIndexVo> index(){
        return mapper.selectIndex();
    }

    @RequestMapping("/detail")
    public ProductDetailVo detail(int id, HttpSession session){
        String info = (String)session.getAttribute("view"+id);
        if(info==null){
            mapper.updateViewCountById(id);
            session.setAttribute("view"+id,"visited");
        }

        return mapper.selectDetailById(id);
    }

    @RequestMapping("/category")
    public List<ProductIndexVo> category(int id){
        return mapper.selectByCategoryId(id);
    }

    @RequestMapping("/search")
    public List<ProductIndexVo> search(String wd){
        return mapper.selectByWd(wd);
    }

}
